package com.jeremyaburns.oddio 
{
	import flash.events.SampleDataEvent;
	import flash.media.Sound;
		
	// Represents a waveform or a sample.  It's essentially just a wrapper for an
	// array of Numbers which represent the samples in the waveform.
	public class Instrument 
	{
		// Allow direct access to the waveform vector, just don't let it become null.
		private var mWaveform :Vector.<Number>;
		public function get waveform() :Vector.<Number> { return mWaveform; }
		
		
		public function Instrument( sampleCount:int = 256 ) 
		{
			mWaveform = new Vector.<Number>( sampleCount );
			mWaveform.fixed = true;
			
			// Default: sine wave.
			for( var i:int = 0 ; i < sampleCount ; ++i ) {
				mWaveform[i] = Math.sin( i / sampleCount *2*Math.PI );
			}
		}
		
		// Given a position in samples and a pitch in samplesPerWave, this returns a value between -0.25 and 0.25.
		internal function getSample( position:int, samplesPerWave:int ) :Number
		{
			if( position < 0 ) return 0;
			position %= samplesPerWave;
			position *= mWaveform.length;
			position /= samplesPerWave;
			return mWaveform[ position ] * 0.25;
		}
		
//== Single note playback interface =============================================================================		
		
		private var playNoteSound :Sound;
		private var playNoteFreq  :int;
		public function playSingleNote( pitch:int ) :void
		{
			if( playNoteSound ) return;
			playNoteFreq = TrackNote.getSamplesPerWaveFromPitch( pitch );
			playNoteSound = new Sound();
			playNoteSound.addEventListener( SampleDataEvent.SAMPLE_DATA, playNote_sampleData );
			playNoteSound.play();
		}
		private function playNote_sampleData( e:SampleDataEvent ) :void
		{
			for( var i:int = 0 ; i < 4096 ; ++i ) {
				var sample:Number = getSample( i, playNoteFreq );
				e.data.writeFloat( sample );
				e.data.writeFloat( sample );
			}
			playNoteSound.removeEventListener( SampleDataEvent.SAMPLE_DATA, playNote_sampleData );
			playNoteSound = null;
		}
	}
}

















